package net.net23.sysdent.server.jdo.control;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.net23.sysdent.server.jdo.pojos.Tag;

public class TagController {

	public static String DEFAULTTAG = "default";

	@SuppressWarnings("unchecked")
	public static Tag getTagByNameAndUser(String name, Long user) {
		PersistenceManager persistenceManager = PMF.get()
				.getPersistenceManager();
		Query query = persistenceManager.newQuery(Tag.class);
		query.setFilter("name == nameParam && user == userParam");
		query.declareParameters("String nameParam, Long userParam");
		try {
			List<Tag> list = (List<Tag>) query.execute(name, user);
			if (list.isEmpty()) {
				return null;
			}
			return list.get(0);
		} finally {
			persistenceManager.close();
		}
	}

	@SuppressWarnings("unchecked")
	public static List<Tag> getTagsByUser(Long user) {
		PersistenceManager persistenceManager = PMF.get()
				.getPersistenceManager();
		Query query = persistenceManager.newQuery(Tag.class);
		query.setFilter("user == userParam");
		query.declareParameters("Long userParam");
		return (List<Tag>) query.execute(user);
	}

	public static Tag forceTagByNameAndUser(String name, long user) {
		Tag tag = TagController.getTagByNameAndUser(name, user);
		if (tag == null) {
			tag = TagController.save(name, "", user);
		}
		return tag;
	}

	public static Tag save(String name, String description, long user) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Tag tag = new Tag(name, description, user);
		pm.makePersistent(tag);
		return tag;
	}

}
